package com.study.httpserver.handler;

import com.study.httpserver.htserver.NotFoundHandler;
import com.study.httpserver.itf.Context;
import com.study.httpserver.itf.impl.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.channels.SelectionKey;

/**
 * Created by meen on 2017/12/5.
 */
public class HttpHandler implements Runnable {

    private Logger logger = LoggerFactory.getLogger(HttpHandler.class);
    //就绪的I/O键
    private SelectionKey key;

    //http请求字符串
    private String requestHeader;

    public HttpHandler(String requestHeader, SelectionKey key) {
        this.key = key;
        this.requestHeader = requestHeader;
    }

    @Override
    public void run() {
        //初始化上下文
        Context context = new HttpContext(requestHeader, key);
        //得到uri
        String uri = context.getRequest().getUri();
        logger.info("得到了uri " + uri);
        //得到MapHandler集合(uri-->handler)
        Handler handler = MapHandler.getContextMapInstance().getHandlerMap().get(uri);
        //找不到对应的handler
        if (handler == null) {
            //404Handler进行处理
//            handler = new NotFoundHandler();
        }
        //初始化handler并执行
        handler.service(context);
    }
}
